import { request } from '@tarojs/taro';
import { getStorage } from './storage';

// 定义基础请求配置类型
type HttpConfig = {
  baseURL?: string;
  timeout?: number;
  headers?: Record<string, string>;
};

// 定义响应结构
interface HttpResponse<T = any> {
  code: number;
  data: T;
  message?: string;
}

// 创建HTTP客户端
function createHttpClient(config: HttpConfig = {}) {
  const defaultConfig: HttpConfig = {
    baseURL: process.env.TARO_APP_API_BASE,
    timeout: 15000,
    headers: {
      'Content-Type': 'application/json'
    }
  };

  const mergedConfig = { ...defaultConfig, ...config };

  // 请求拦截器
  const requestInterceptor = (options: { url: any; header: any; timeout: any }) => {
    options.header = { ...options.header };

    // 添加认证token示例（根据实际需求修改）
    const token = getStorage('token');
    if (token) {
      options.header['Authorization'] = `Bearer ${token}`;
    }

    return options;
  };

  // 响应拦截器
  // @ts-ignore
  const responseInterceptor = <T>(response: request.SuccessCallbackResult<T>): HttpResponse<T> => {
    // 这里处理通用响应格式，根据后端接口调整
    if (response.statusCode >= 200 && response.statusCode < 300) {
      return {
        code: response.statusCode,
        data: response.data
      };
    }
    throw new Error(`请求失败，状态码：${response.statusCode}`);
  };

  return {
    async request<T = any>(options: { url?: any; header: any }): Promise<HttpResponse<T>> {
      try {
        const mergedOptions = requestInterceptor({
          ...options,
          url: mergedConfig.baseURL + options.url,
          header: { ...mergedConfig.headers, ...options.header },
          timeout: mergedConfig.timeout
        });

        const response = await request<T>(mergedOptions);
        return responseInterceptor<T>(response);
      } catch (error) {
        console.error('请求异常:', error);
        throw error;
      }
    },

    get<T = any>(url: string, params?: Record<string, any>): Promise<HttpResponse<T>> {
      // @ts-ignore
      return this.request<T>({
        url,
        method: 'GET',
        data: params
      });
    },

    post<T = any>(url: string, data?: any): Promise<HttpResponse<T>> {
      // @ts-ignore
      return this.request<T>({
        url,
        method: 'POST',
        data
      });
    }
  };
}

// 默认实例
const http = createHttpClient();

export default http;
